package com.hongx.zhibo;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hongx.zhibo.utils.DisplayUtil;
import com.hongx.zhibo.utils.HorizontalListView;
import com.hongx.zhibo.utils.MagicTextView;
import com.hongx.zhibo.utils.SoftKeyBoardListener;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author: fuchenming
 * @create: 2020-02-01 15:50
 */
public class LayerFrag2 extends Fragment implements View.OnClickListener {

    // 礼物
    private int[] GiftIcon = new int[]{R.drawable.zem72,
            R.drawable.zem70,
            R.drawable.zem68,
            R.drawable.zem63};

    private NumberAnim giftNumberAnim;
    private List<String> messageData = new LinkedList<>();
    private MessageAdapter messageAdapter;
    private ListView lv_message;
    private HorizontalListView hlv_audience;
    private RecyclerView ll_gift_recycler;
    private TranslateAnimation outAnim;
    private TranslateAnimation inAnim;
    private LinearLayout ll_inputparent;
    private Button tv_chat;
    private TextView tv_send;
    private EditText et_chat;
    private LinearLayout ll_anchor;
    private RelativeLayout rl_num;

    private Context myContext;
    private Button btn_gift01;
    private Button btn_gift02;
    private Button btn_gift03;
    private Button btn_gift04;

    private View view;
    private NewAdapter liveAdapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.frag_layer2, null);
        myContext = getActivity();
        initView(view);
        initData();
        return view;
    }


    public void initView(View view) {
        lv_message = view.findViewById(R.id.lv_message);
        hlv_audience = view.findViewById(R.id.hlv_audience);
        ll_gift_recycler = view.findViewById(R.id.ll_gift_recycler);
        ll_inputparent = view.findViewById(R.id.ll_inputparent);
        tv_chat = view.findViewById(R.id.tv_chat);
        tv_send = view.findViewById(R.id.tv_send);
        et_chat = view.findViewById(R.id.et_chat);
        ll_anchor = view.findViewById(R.id.ll_anchor);
        rl_num = view.findViewById(R.id.rl_num);
        btn_gift01 = view.findViewById(R.id.btn_gift01);
        btn_gift02 = view.findViewById(R.id.btn_gift02);
        btn_gift03 = view.findViewById(R.id.btn_gift03);
        btn_gift04 = view.findViewById(R.id.btn_gift04);

        LinearLayoutManager layout = new LinearLayoutManager(getContext());
        layout.setStackFromEnd(true);//列表再底部开始展示，反转后由上面开始展示
        layout.setReverseLayout(true);//列表翻转
        ll_gift_recycler.setLayoutManager(layout);
        liveAdapter = new NewAdapter(getActivity(), new ArrayList<>());
        ll_gift_recycler.setAdapter(liveAdapter);
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                for (int i = 0; i < liveAdapter.getDatas().size(); i++) {
                    ItemBean data = liveAdapter.getDatas().get(i);
                    long l = System.currentTimeMillis() - data.time;
                    if (data.type == 1 && l > 9000) {
                        data.type = 0;
                        int finalI = i;
                        ll_gift_recycler.post(() -> liveAdapter.notifyItemChanged(finalI));
                    }
                }
            }
        }, 0, 1000);
        ll_gift_recycler.setItemAnimator(new MyItemAnimator(liveAdapter,getActivity()));
    }

    private void initData() {
        initAudience(); // 初始化观众
        initMessage(); // 初始化评论
        initListener();

        initAnim(); // 初始化动画
    }

    /**
     * 初始化观众列表
     */
    private void initAudience() {
        hlv_audience.setAdapter(new AudienceAdapter(myContext));
    }

    /**
     * 初始化评论列表
     */
    private void initMessage() {
        for (int x = 0; x < 20; x++) {
            messageData.add("小明: 主播好漂亮啊" + x);
        }
        messageAdapter = new MessageAdapter(getActivity(), messageData);
        lv_message.setAdapter(messageAdapter);
        lv_message.setSelection(messageData.size());
    }

    private void initListener() {
        btn_gift01.setOnClickListener(this);
        btn_gift02.setOnClickListener(this);
        btn_gift03.setOnClickListener(this);
        btn_gift04.setOnClickListener(this);
        tv_chat.setOnClickListener(this);
        tv_send.setOnClickListener(this);

        view.setOnClickListener(v -> {
            if (ll_inputparent.getVisibility() == View.VISIBLE) {
                tv_chat.setVisibility(View.VISIBLE);
                ll_inputparent.setVisibility(View.GONE);
                hideKeyboard();
            }
        });

        // 软键盘监听
        SoftKeyBoardListener.setListener(getActivity(), new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {/*软键盘显示：执行隐藏title动画，并修改listview高度和装载礼物容器的高度*/

                // 输入文字时的界面退出动画
                AnimatorSet animatorSetHide = new AnimatorSet();
                ObjectAnimator leftOutAnim = ObjectAnimator.ofFloat(rl_num, "translationX", 0, -rl_num.getWidth());
                ObjectAnimator topOutAnim = ObjectAnimator.ofFloat(ll_anchor, "translationY", 0, -ll_anchor.getHeight());
                animatorSetHide.playTogether(leftOutAnim, topOutAnim);
                animatorSetHide.setDuration(300);
                animatorSetHide.start();
                // 改变listview的高度
                dynamicChangeListviewH(90);
            }

            @Override
            public void keyBoardHide(int height) {/*软键盘隐藏：隐藏聊天输入框并显示聊天按钮，执行显示title动画，并修改listview高度和装载礼物容器的高度*/
                tv_chat.setVisibility(View.VISIBLE);
                ll_inputparent.setVisibility(View.GONE);
                // 输入文字时的界面进入时的动画
                AnimatorSet animatorSetShow = new AnimatorSet();
                ObjectAnimator leftInAnim = ObjectAnimator.ofFloat(rl_num, "translationX", -rl_num.getWidth(), 0);
                ObjectAnimator topInAnim = ObjectAnimator.ofFloat(ll_anchor, "translationY", -ll_anchor.getHeight(), 0);
                animatorSetShow.playTogether(leftInAnim, topInAnim);
                animatorSetShow.setDuration(300);
                animatorSetShow.start();

                // 改变listview的高度
                dynamicChangeListviewH(150);
            }
        });

    }

    /**
     * 初始化动画
     */
    private void initAnim() {
        giftNumberAnim = new NumberAnim(); // 初始化数字动画
        inAnim = (TranslateAnimation) AnimationUtils.loadAnimation(getActivity(), R.anim.gift_in); // 礼物进入时动画
        outAnim = (TranslateAnimation) AnimationUtils.loadAnimation(getActivity(), R.anim.gift_out); // 礼物退出时动画
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_gift01: // 礼物1,送香皂
                addItem(GiftIcon[0]);
                break;
            case R.id.btn_gift02: // 礼物2,送玫瑰
                addItem(GiftIcon[1]);
                break;
            case R.id.btn_gift03: // 礼物3,送爱心
                addItem(GiftIcon[2]);
                break;
            case R.id.btn_gift04: // 礼物4,送蛋糕
                addItem(GiftIcon[3]);
                break;
            case R.id.tv_chat:// 聊天
                tv_chat.setVisibility(View.GONE);
                ll_inputparent.setVisibility(View.VISIBLE);
                ll_inputparent.requestFocus(); // 获取焦点
                showKeyboard();
                break;
            case R.id.tv_send:// 发送消息
                String chatMsg = et_chat.getText().toString();
                if (!TextUtils.isEmpty(chatMsg)) {
                    messageData.add("小明: " + chatMsg);
                    et_chat.setText("");
                    messageAdapter.NotifyAdapter(messageData);
                    lv_message.setSelection(messageData.size());
                }
                hideKeyboard();
                break;
        }
    }

    public void addItem(int gitid) {
        List<ItemBean> datas = liveAdapter.getDatas();
        if (datas.isEmpty()) {
            datas.add(new ItemBean(1, gitid, 1, System.currentTimeMillis()));
            liveAdapter.notifyItemChanged(0);
            return;

        } else
            for (int i = 0; i < datas.size(); i++) {
                ItemBean bean = datas.get(i);
                if (bean.type == 1 && bean.gifId == gitid) {
                    bean.count += 1;
                    bean.time = System.currentTimeMillis();
                    Log.w("TAG", "addItem: 来更新数据");
                    liveAdapter.notifyDataSetChanged();
                    return;

                }
            }
        for (int i = 0; i < datas.size(); i++) {
            ItemBean bean = datas.get(i);
            if (bean.type == 0) {
                Log.e("TAG", "addItem: 来添加数据");
                datas.set(i, new ItemBean(1, gitid, 1, System.currentTimeMillis()));
                liveAdapter.notifyDataSetChanged();
                return;
            }
        }
        for (int i = 0; i < datas.size(); i++) {
            if (datas.size() < 4) {
                datas.add(new ItemBean(1, gitid, 1, System.currentTimeMillis()));
                // liveAdapter.notifyItemChanged(i + 1);
                liveAdapter.notifyDataSetChanged();
                break;
            }
        }
        //liveAdapter.notifyDataSetChanged();
    }

    public class NumberAnim {
        private Animator lastAnimator;

        public void showAnimator(View v) {

            if (lastAnimator != null) {
                lastAnimator.removeAllListeners();
                lastAnimator.cancel();
                lastAnimator.end();
            }
            ObjectAnimator animScaleX = ObjectAnimator.ofFloat(v, "scaleX", 1.3f, 1.0f);
            ObjectAnimator animScaleY = ObjectAnimator.ofFloat(v, "scaleY", 1.3f, 1.0f);
            AnimatorSet animSet = new AnimatorSet();
            animSet.playTogether(animScaleX, animScaleY);
            animSet.setDuration(200);
            lastAnimator = animSet;
            animSet.start();
        }
    }


    /**
     * 显示软键盘
     */
    private void showKeyboard() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(et_chat, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 隐藏软键盘
     */
    public void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(et_chat.getWindowToken(), 0);
    }


    /**
     * 动态的修改listview的高度
     */
    private void dynamicChangeListviewH(int heightPX) {
        ViewGroup.LayoutParams layoutParams = lv_message.getLayoutParams();
        layoutParams.height = DisplayUtil.dip2px(getActivity(), heightPX);
        lv_message.setLayoutParams(layoutParams);
    }


}
